package com.linln.admin.pcs.service;

import com.linln.modules.system.domain.PayParam;
import com.linln.modules.system.util.WeChatPayUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@Service
public class WeChatPayService {

    // 统一下单接口URL
    private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";


    // 生成预支付订单
    public Map<String, String> createOrder(PayParam payParam) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appid", payParam.getAppId()); // 应用ID
        params.put("mch_id", payParam.getMchId()); // 商户号
        params.put("nonce_str", generateNonceStr()); // 随机字符串
        params.put("body", payParam.getBody()); // 商品描述
        params.put("out_trade_no", payParam.getOutTradeNo()); // 商户订单号
        params.put("total_fee", String.valueOf(payParam.getTotalFee())); // 总金额（分）
        params.put("spbill_create_ip", payParam.getClientIp()); // 客户端IP
        params.put("notify_url", payParam.getNotifyUrl()); // 回调地址
        params.put("trade_type", "MWEB"); // 交易类型

        // 生成签名
        params.put("sign", WeChatPayUtil.generateSign(params, payParam.getApiKey()));

        // 转换为XML并发送请求
        String xml = toXml(params);
        String responseXml = post(UNIFIED_ORDER_URL, xml);

        // 解析返回结果
        Map<String, String> result = WeChatPayUtil.parseXml(responseXml);
        return result;
    }

    // 生成随机字符串
    private String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    // 发送POST请求
    private String post(String url, String xml) throws Exception {
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.getOutputStream().write(xml.getBytes("UTF-8"));

        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    // 转换Map为XML
    private String toXml(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append("</").append(entry.getKey()).append(">");
        }
        sb.append("</xml>");
        return sb.toString();
    }
}
